package com.jason.learn.springcloud.orderservice.service.rocketmq;

import com.alibaba.nacos.common.utils.ConcurrentHashSet;
import com.jason.learn.springcloud.orderservice.dao.OrderDao;
import com.jason.learn.springcloud.orderservice.enty.BuyOrder;
import org.apache.rocketmq.spring.annotation.RocketMQTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionListener;
import org.apache.rocketmq.spring.core.RocketMQLocalTransactionState;
import org.apache.rocketmq.spring.support.RocketMQHeaders;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.messaging.Message;

import java.util.concurrent.ConcurrentHashMap;

@RocketMQTransactionListener(txProducerGroup = "orderTxProducerGroup")
public class TransactionListenerImpl implements RocketMQLocalTransactionListener {
    private Logger logger = LoggerFactory.getLogger(TransactionListenerImpl.class);
    private ConcurrentHashMap<String, Integer> localTrans = new ConcurrentHashMap<String, Integer>();
    private static int maxTryMums = 3;
    @Autowired
    private OrderDao orderDao;
    private ConcurrentHashMap<String,RocketMQLocalTransactionState> dealedSet = new ConcurrentHashMap<>();

    @Override
    public RocketMQLocalTransactionState executeLocalTransaction(Message message, Object buyOrder) {
        String transId = (String)message.getHeaders().get(RocketMQHeaders.PREFIX+RocketMQHeaders.TRANSACTION_ID);
        BuyOrder order = (BuyOrder)buyOrder;
        logger.info("监听到消息"+transId);
        try{
            orderDao.updateOrder(order,1);
        }catch (Exception e){
            logger.error(e.getMessage(),e);
            dealedSet.put(transId,RocketMQLocalTransactionState.ROLLBACK);
            return RocketMQLocalTransactionState.ROLLBACK;
        }
        dealedSet.put(transId,RocketMQLocalTransactionState.COMMIT);
        logger.info("处理完返回");
        return RocketMQLocalTransactionState.COMMIT;
    }

    @Override
    public RocketMQLocalTransactionState checkLocalTransaction(Message message) {
        String transId = (String)message.getHeaders().get(RocketMQHeaders.PREFIX+RocketMQHeaders.TRANSACTION_ID);
        RocketMQLocalTransactionState state = dealedSet.get(transId);
        if(null == state) {
            logger.info("回查消息 -> transId = " + transId + "状态还未知 ");
            return RocketMQLocalTransactionState.UNKNOWN;
        }else{
            logger.info("回查消息 -> transId = " + transId + ", state = " + state);
            return state;
        }
    }
}
